package com.example.dw.config;

import com.example.dw.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证过滤器
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    // 不需要认证的接口
    private static final List<String> EXCLUDED_PATHS = Arrays.asList(
            "/user/register",
            "/user/login",
            "/user/login/code",
            "/user/wechat/login",
            "/user/user/pack",
            "/user/auth/qrcode/generate",
            "/user/auth/qrcode/check",
            "/home/",
            "/active/getActiveByPageIng",
            "/active/getActiveByPageEd",
            "/active/getAllBigTypeByPage",
            "/active/activeByMonth",
            "/active/activeByMonthAll",
            "/active/getActivedByPage",
            "/active/getQR",
            "/active/commentPageE/",
            "/course/getCourseByType",
            "/course/getAllType",
            "/course/getCourseMOHu",
            "/course/getCourseByTypePage",
            "/wcnimbiejinlaishouyangluyifaq12/78nongdaoyidibusgun8"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String requestPath = request.getServletPath();
        
        // 跳过不需要认证的路径
        if (shouldSkipFilter(requestPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        String authorizationHeader = request.getHeader("Authorization");
        
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            
            try {
                if (jwtUtil.validateToken(token)) {
                    String username = jwtUtil.getUsernameFromToken(token);
                    
                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                        
                        UsernamePasswordAuthenticationToken authToken = 
                                new UsernamePasswordAuthenticationToken(
                                        userDetails, null, userDetails.getAuthorities());
                        authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        SecurityContextHolder.getContext().setAuthentication(authToken);
                        
                        // 将用户ID存储到request属性中，供Controller使用
                        Integer userid = jwtUtil.getUserIdFromToken(token);
                        request.setAttribute("userid", userid);
                    }
                }
            } catch (Exception e) {
                log.error("JWT认证失败: {}", e.getMessage());
            }
        }
        
        filterChain.doFilter(request, response);
    }

    private boolean shouldSkipFilter(String requestPath) {
        // 检查是否是活动详情路径 /active/{id}
        if (requestPath.matches("/active/\\d+")) {
            return true;
        }
        
        return EXCLUDED_PATHS.stream().anyMatch(requestPath::startsWith);
    }
} 